package com.cn.por.util.io;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 
 * @author 26983 图片处理工具
 *
 */
public class ImageUtil {

	/**
	 * 生成文字图片
	 * 
	 * @param text
	 */
	/**
	 * @param text
	 */
	/**
	 * @param text
	 */
	public static void generateImage(String text) {

		int width = 60;
		int height = 60;
		String s = text;

		File file = new File("C:\\Users\\26983\\Desktop\\room.jpg");

		Font font = new Font("Serif", Font.CENTER_BASELINE, 10);

		// 1.创建空白图片
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 2.获取图片画笔
		Graphics2D graphic = (Graphics2D) image.getGraphics();
		
		graphic.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));
		
		
		graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		// 3.设置画笔颜色
		graphic.setColor(Color.white);
		
		
		graphic.fillRoundRect(0, 0, width, height, 20, 20);
		graphic.fillRect(0, 0, width, height);
		
		graphic.setColor(Color.black);
		FontRenderContext context = graphic.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(s, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = -bounds.getY();
		double baseY = y + ascent;
		// 绘制字符串
		graphic.drawString(s, (int) x, (int) baseY);

		try {
			// 将生成的图片保存为jpg格式的文件。ImageIO支持jpg、png、gif等格式
			ImageIO.write(image, "jpg", file);
		} catch (IOException e) {
			System.out.println("生成图片出错........");
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		generateImage("餐厅");
	}

	public static BufferedImage convertCircular(BufferedImage bi1) throws IOException {
		// 透明底的图片
		BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_RGB);
		Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
		Graphics2D g2 = bi2.createGraphics();
		g2.setClip(shape);
		// 使用 setRenderingHint 设置抗锯齿
		g2.drawImage(bi1, 0, 0, null);
		// 设置颜色
		g2.setBackground(Color.green);
		g2.dispose();

		return bi2;
	}

}
